// 通用功能
// 1. 获取系统时间
// 2. 判断文件是否存在
// 3. 获取文件所在目录
// 4. 创建目录
#pragma once
#include <sys/stat.h>
#include <sys/types.h>

#include <ctime>
#include <iostream>
using std::cout;
using std::endl;

namespace xqlog {
namespace Util {
class Date {
   public:
    static time_t Now() { return time(nullptr); }
};
class File {
   public:
    static bool Exists(const std::string &filename) {
        // return (0==access(filename.c_str(),F_OK)); 不具有可移植性，仅在linux上可以跑 \
        采用POSIX提供的stat
        struct stat st;
        return (0 == stat(filename.c_str(), &st));
    }
    static std::string Path(const std::string &filename) {
        if (filename.empty()) return "";
        int pos = filename.find_last_of("/\\");
        if (pos != std::string::npos) return filename.substr(0, pos + 1);
        return "";
    }
    static void CreateDirectory(const std::string &pathname) {
        if (pathname.empty()) perror("文件所给路径为空：");
        // 文件不存在再创建
        if (!Exists(pathname)) {
            size_t pos, index = 0;
            size_t size = pathname.size();
            while (index < size) {
                pos = pathname.find_first_of("/\\", index);
                if (pos == std::string::npos) {
                    mkdir(pathname.c_str(), 0755);
                    return;
                }
                if (pos == index) {
                    index = pos + 1;
                    continue;
                }

                std::string sub_path = pathname.substr(0, pos);
                if (sub_path == "." || sub_path == "..") {
                    index = pos + 1;
                    continue;
                }
                if (Exists(sub_path)) {
                    index = pos + 1;
                    continue;
                }

                mkdir(sub_path.c_str(), 0755);
                index = pos + 1;
            }
        }
    }
};  // class file
}  // namespace Util
}  // namespace xqlog
